//
//  ZMTabBar.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/7/21.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit

protocol ZMTabBarProtool : NSObjectProtocol{
    func tabBarDidSelect(tabBar : ZMTabBar,index : Int)
}

class ZMTabBar: UIView {
    
    weak var delegate : ZMTabBarProtool?
    
    var selButton : UIButton?
    
    var secendBtn : UIButton?
    
     var items : [UITabBarItem]!{
    
    
        didSet{
        
            for temp in items {
                let bgView = UIView()
                addSubview(bgView)
                
                let btn = UIButton(type: .custom)
                bgView.addSubview(btn)
                
//                btn.adjustsImageWhenHighlighted = false

                btn.setImage(temp.image, for: .normal)
                btn.setImage(temp.selectedImage, for: .selected)
                
                
            
                btn.addTarget(self, action: #selector(buttonOnClick(btn:)), for: .touchUpInside)
                
            }
        
        
        
        }
    
    
    }
    
    
    func buttonOnClick(btn : UIButton){
        
        selButton?.isSelected = false
        
        selButton?.isUserInteractionEnabled = true
        
        btn.isSelected = true
        
        btn.isUserInteractionEnabled = false
        
        
        
        selButton = btn
        
        
        
        delegate?.tabBarDidSelect(tabBar: self, index: btn.tag)
        
 
        
    }
    
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let itemY : CGFloat = 0
        let itemW = frame.size.width / CGFloat(items.count)
        let itemH = frame.size.height
        
        for (idex,tempView) in subviews.enumerated() {
            
            tempView.frame = CGRect(x: itemW * CGFloat(idex), y: itemY, width: itemW, height: itemH)
            
            for btn in tempView.subviews {
                let button =  btn as! UIButton
                button.frame = tempView.bounds
                button.tag = idex
                
                if button.tag == 0 {
                    
                    button.isSelected = true
                    
                    button.isUserInteractionEnabled = false
                    
                    selButton = button
                }
                
                
                
                if button.tag == 1 {
                    secendBtn = button
                }
                
                
            }
            
  
        }
        
        
        
        
    }
    

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
